
/**
 * @author kris
 * 
 */
public class PercolationStats {

private Percolation p;
	private int N;
	private int T;
	private double size;
	private double[] thresholds;
	private boolean[] sitesAlreadyPicked;

	public PercolationStats(int N, int T) {
		validate(N, T);
		this.N = N;
		this.T = T;
		this.size = N * N;
		thresholds = new double[T];
		performExperiment();
	}

	private void performExperiment() {
		for (int i = 0; i < T; i++) {
			p = new Percolation(N);
			sitesAlreadyPicked = new boolean[N*N];
			double counter = 0;
			do {
				int siteIndex = 0;
				int row = 0;
				int column = 0;
				boolean alreadyPicked = false;
				do {
				row = StdRandom.uniform(1, N + 1);
				column = StdRandom.uniform(1, N + 1);
				siteIndex = ((row-1) * N) + (column-1);
				alreadyPicked = sitesAlreadyPicked[siteIndex];
				} while (alreadyPicked);

				sitesAlreadyPicked[siteIndex] = true;

				p.open(row, column);

				counter++;
			} while (!p.percolates());
			thresholds[i] = counter / size;
		}
	}

	/**
	 * sample mean of percolation threshold
	 * 
	 * @return
	 */
	public double mean() {
		return StdStats.mean(thresholds);
	}

	/**
	 * sample standard deviation of percolation threshold
	 * 
	 * @return
	 */
	public double stddev() {
		return StdStats.stddev(thresholds);
	}

	/**
	 * returns lower bound of the 95% confidence interval
	 * 
	 * @return
	 */
	public double confidenceLo() {
		return StdStats.mean(thresholds) - ((1.96 * stddev()) / Math.sqrt(T));
	}

	/**
	 * returns upper bound of the 95% confidence interval
	 * 
	 * @return
	 */
	public double confidenceHi() {
		return StdStats.mean(thresholds) + ((1.96 * stddev()) / Math.sqrt(T));
	}

	private void validate(int n, int t) {
		if (n < 0 || t < 0) {
			throw new IllegalArgumentException();
		}
	}

	public static void main(String[] args) {
		int N = Integer.valueOf(100);
		int T = Integer.valueOf(100);
//		Stopwatch watch = new Stopwatch();
		PercolationStats stats = new PercolationStats(N, T);
		stats.performExperiment();
//		double elapsedTime = watch.elapsedTime();
//		System.out.println("elapsed time: " + elapsedTime + " s");
		System.out.println("mean = " + stats.mean());
		System.out.println("stddev = " + stats.stddev());
		System.out.println("95% confidence interval  =" +stats.confidenceLo()
				+ ", " + stats.confidenceHi());
	}
}